package adv8.server1;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

/**
 * @author oldliu
 * @since 1.0
 */
public class WechatServer {
    public static void main(String[] args) {
        try {
            ServerSocket st = new ServerSocket(8888);
            System.out.println("聊天服务器启动。。。");
            while (true) {
                Socket s = st.accept();
                System.out.println("有人连接上了。。。" + s);
                System.out.println(s.getInetAddress() + ":" + s.getPort());
                System.out.println(s.getLocalAddress() + ":" + s.getLocalPort());

                InputStream in = s.getInputStream();
                OutputStream out = s.getOutputStream();
                //聊天
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                PrintWriter pw = new PrintWriter(out, true);//true表示自动刷新
                String line = null;
                try {
                    while ((line = br.readLine()) != null) {
                        System.out.println(s + "说:" + line);
                        pw.println("你说的话:" + line + "，朕知道了" + new Date());
                        //pw.flush();
                        if ("byebye".equals(line)) {
                            break;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    s.close();//隐患
                    System.out.println(s + "关闭连接");
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
